package middleware

import (
	"github.com/gin-gonic/gin"
	"huijing_mall/shared/common"
	"huijing_mall/shared/get_ctx_value"
	"huijing_mall/variable"

	"huijing_mall/pkg/auth"
	"huijing_mall/pkg/logger"
)

// AuthMiddleware 是一个身份验证中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(g *gin.Context) {
		dbs := get_ctx_value.GetDBS(g)
		if uid, ok := auth.VerifyCookie(&dbs, g.Request.Cookies()); ok {
			g.Set(variable.UID, uid)
			common.GetUserIp(g)
			logger.Info("追加写入文件成功")
			// 如果认证通过，继续处理请求
			g.Next()
			return
		}
		common.GetUserIp(g)
		logger.Info("无效的认证令牌")
		//认证不通过 返回
		g.AbortWithStatusJSON(200, gin.H{"code": -1, "message": "无效的认证令牌", "data": nil})
		return
	}
}
